var options, layer, table, form, upload, element, laytpl;
var uploads_url = $("#uploads_url").val();
var admin_map = $("#admin_map").val();
var uploadVideo = $("#uploadVideo").val();
//layui初始化，加载弹出层，表单等
layui.use(['form', 'upload', 'table', 'laypage', 'element', 'laytpl'], function () {
    layer = layui.layer;
    form = layui.form;
    table = layui.table;
    upload = layui.upload;
    element = layui.element;
    laytpl = layui.laytpl;
    // layer.config({
    //     skin: 'dark-blue'
    // })


    function setStorage(key, value) {
        if (!window.localStorage) {
            console.log("浏览器不支持localstorage");
            return false;
        } else {
            window.localStorage.setItem(key, value);
            return true;
        }
    }

    let themeStyle = {
        theme: {
            color: {
                main: '#03152A'
                , logo: '#03152A'
                , selected: '#1E9FFF'
                , header: ''
                , alias: 'dark-blue' //海洋头
                , index: 0
            }
        }
    }
    setStorage('layuiAdmin', JSON.stringify(themeStyle));

    $(".openMaterial").click(function () {
        var count = $(this).attr('data-count');
        var id = $(this).attr('data-id');
        var name = $(this).attr('data-name');
        // var width = $(this).attr('data-width') ? $(this).attr('data-width') : '90%';

        var h = $(window).height() <= (650 * 1.2) ? '90%' : '650px';
        layer.open({
            type: 2,
            area: ['1000px', h],
            btn: ['确认', '取消'],
            fix: false, //不固定
            maxmin: true,
            shadeClose: true,
            shade: 0.4,
            anim: 2,
            title: '选择图片',
            content: '/' + admin_map + '/materialLibrary/open.html?count=' + count + '&id=' + id + "&name=" + name,
            yes: function (index, layero) {
                var body = layer.getChildFrame('body', index);
                var a = body.find('#selectedUrl').val();
                var n = a.split(',');
                var tpl = document.getElementById('openMaterialTemplate').innerHTML;
                laytpl(tpl).render({data: n, name: name}, function (html) {
                    $("#" + id).html(html);
                });
                layer.closeAll();
            }
        });
    });


    element.on('tab(layadmin-layout-tabs)', function (data) {
        console.log(this); //当前Tab标题所在的原始DOM元素
        console.log(data.index); //得到当前Tab的所在下标
        console.log(data.elem); //得到当前的Tab大容器
    });

    // input 监听回车事件
    $(".nav_search input").keydown(function (e) {
        // 当 keyCode 是13时,是回车操作
        if (e.keyCode == 13) {
            table.reload('form_table', {
                where: form.val("search-form")
                , page: {
                    curr: 1
                }
            });
            $(".resetSearch").show();
            e.preventDefault();
            return false;
        }
    })


    form.on('submit(search)', function (data) {
        table.reload('form_table', {
            where: form.val("search-form")
            , page: {
                curr: 1
            }
        });
        $(".resetSearch").show();
        return false;
    });

    form.on('submit(resetSearch)', function (data) {
        $(".search-form")[0].reset();
        table.reload('form_table', {
            where: form.val("search-form")
            , page: {
                curr: 1
            }
        });
        $(".resetSearch").hide();
        return false;
    });

    //监听表格左侧工具栏
    table.on('tool(table)', function (obj) {
        try {
            tableTool(obj);
        } catch (e) {
            alert('发生错误了');
        }
    });

    //触发排序事件
    table.on('sort(table)', function (obj) {
        table.reload('form_table', {
            initSort: obj
            , where: {
                tableSortField: obj.field
                , tableSortOrder: obj.type
                , tableSearch: form.val("search-form")
            }
        });
    });
    //监听开关状态栏
    form.on('switch(status)', function (obj) {
        buttons.save(this.value, obj.elem.attributes[1].value, obj.elem.checked, $("#update_url").val());
    });
    form.on('switch(switch_old)', function (obj) {
        var val = $(this).prop('checked');
        var url = $(this).attr('url');
        $.get(url, {val: val})
    })
    form.on('switch(switch)', function (obj) {
        var val = $(this).prop('checked');
        var url = $(this).attr('url');
        $.get(url, {val: val})
    })
    //表单验证
    form.verify();

    form.on('select(tableInput)', function (obj) {
        tableInput($(obj.elem));
    });

    //添加配置页面，监听日期配置
    form.on('select(call_type)', function (obj) {
        if (obj.value == '7') {
            $("#time_format").css('display', 'block');
        } else {
            $("#time_format").css('display', 'none');
        }
    });

    //监听表单提交
    form.on('submit(save)', function (data) {
        layerLoad();
        var btn = $(this);
        btn.attr('disabled', true);
        formObj = $($(this).attr('formObj'));
        url = formObj.attr('action');
        var back_url = btn.attr('data-back-url');
        $.ajax({
            type: 'POST',
            url: url,
            data: formObj.serialize(),
            dataType: "json",
            success: function (data) {
                layer.closeAll();
                if (data.code == 1) {
                    notify.success(data.msg, 1500, function () {
                        if (back_url) {
                            parent.layui.index.refreshAndCloseTabs(back_url, true);
                        } else {
                            if (window.name != '') {
                                var index = parent.layer.getFrameIndex(window.name);
                                parent.layer.close(index);
                                parent.window.location.reload();
                            } else {
                                window.location.reload();
                            }
                        }

                    });

                } else {
                    notify.error(data.msg);
                    btn.removeAttr('disabled');
                }
            },
            error(e) {
                layer.closeAll();
                btn.removeAttr('disabled');
            }
        });
        return false;
    })

    //单张图片上传
    upload.render({
        elem: '.uploadImage',
        url: uploads_url,
        before: function (obj) {
            layer.load();
            var showImage = this.item.find('.showImage');
            obj.preview(function (index, file, result) {
                showImage.attr('src', result)
            });
        },
        done: function (data) {
            layer.closeAll();
            if (data.code == 200) {
                this.item.find('.inpImage').val(data.data.url);
                notify.success(data.msg);
            } else {
                notify.error(data.msg);
            }
        },
        error: function () {
            layer.closeAll('loading');
        }
    });

    $('.showImages').on('click', '.uploadDels', function () {
        $(this).parent('.w_imgCon').remove();
    }).on('click', '.uploadDels', function () {
        var i = $(this).index('.uploadDels');
        $('.uploadImageBoxes:eq(' + i + ')').remove();
    })

    //单文件上传
    upload.render({
        elem: '.uploadVideo',
        url: uploadVideo,
        accept: 'file'
        ,before: function(obj){
            element.progress('demo', '0%'); //进度条复位
            layer.msg('上传中', {icon: 16, time: 0});
        },
        progress: function(n, elem, res, index){
            console.log(index);
            element.progress('demo', n + '%'); //进度条

        },
        done: function (data) {
            layer.closeAll();
            if (data.code == 200) {
                this.item.find('.inpVideo').val(data.data.url);
                notify.success(data.msg);
            } else {
                notify.error(data.msg);
            }
        },
        error:function(){
            layer.closeAll('loading');
        }
    });

    $('.layui-card-body').on('click', '.openShowImg', function () {
        otherTool($(this), 'openShowImg');
    }).on('click', '.openShowVideo', function () {
        otherTool($(this), 'openShowVideo');
    }).on('click', '.openEditor', function () {
        var value = $(this).attr("data-value");
        layer.open({
            type: 1,
            area: ['800px', '80%'],
            shade: 0.4,
            shadeClose: true,
            anim: 2,
            title: '预览',
            content: '<div style="padding: 10px">' + value + '</div>'
        });
    }).on('change', '.tableInput', function () {
        tableInput($(this));
    })


    upload.render({
        elem: '.uploadsBtn',
        url: uploads_url,
        multiple: true,
        before: function (obj) {
            var i = this.elem.index('.uploadsBtn');
            notify.loading('上传中...');
        },
        done: function (data) {
            notify.destroyAll();
            if (data.code == 200) {
                var showImage = this.item.parent('.uploadsPrev').find('.showImages');
                var inpName = this.item.parent('.uploadsPrev').find('.uploadsBtn').attr('inpName');
                showImage.append('' +
                    '<li class="w_imgCon" id="addPicture">' +
                    '<img width="80" style="margin-left: 10px;" src="' + data.data.url + '">' +
                    '<img class="whide1 uploadDels" src="http://dms.66km.com/static/img/marketing_delpic.png">\n' +
                    '<input type="hidden" name="' + inpName + '" value="' + data.data.url + '" class="uploadInps"/></li>')
            } else {
                notify.error(data.msg);
            }
        },
        error: function () {
            notify.destroyAll();
            notify.error('上传失败');
        }
    });

    // //多张上传
    // upload.render({
    //     elem: '.uploadImages',
    //     url: uploads_url,
    //     multiple: true,
    //     before: function (obj) {
    //         layer.load();
    //         var i = this.elem.index('.uploadImages');
    //         obj.preview(function (index, file, result) {
    //             $('.showImages:eq(' + i + ')').append('' +
    //                 '<div class="imgContainer uploadImageBoxes">' +
    //                 '<img src="' + result + '" style="max-width: 100%">' +
    //                 '<br/>' +
    //                 '<a href="javascript:;" class="uploadDels">删除</a>' +
    //                 '</div>')
    //         });
    //     },
    //     done: function (data) {
    //         layer.closeAll();
    //         if (data.code == 200) {
    //             var i = this.elem.index('.uploadImages');
    //             var inpName = this.elem.attr('inpName');
    //             $('.showImages:eq(' + i + ')').append('<input type="hidden" name="' + inpName + '[]" value="' + data.data.url + '" class="uploadInps"/>');
    //             notify.success(data.msg);
    //         } else {
    //             notify.error(data.msg);
    //         }
    //     },
    //     error: function () {
    //         layer.closeAll('loading');
    //     }
    // });


    /*富文本编辑器*/
    $('.editor').each(function () {
        UE.getEditor($(this).attr('id'), {scaleEnabled: true});
    })

    /*列表页checkbox开始*/
    tableCheck = {
        init: function () {
            layui.use('form', function () {
                layui.form.on('checkbox(list_all)', function (obj) {
                    var checked = obj.elem.checked;
                    $("[lay-filter=list_checkbox]").prop("checked", checked);
                    layui.form.render('checkbox');
                })
            })
        },
        getData: function () {
            var arr = [];
            $("[lay-filter=list_checkbox]:checked").each(function (i, e) {
                arr.push($(this).val());
            });
            return arr;
        }
    }
    tableCheck.init();
    var cateIds = [];

    function getCateId(cateId) {
        $("tbody tr[fid=" + cateId + "]").each(function (index, el) {
            id = $(el).attr('cate-id');
            cateIds.push(id);
            getCateId(id);
        });
    }

    $("tbody.x-cate tr[level!='0']").hide();

    //修改字段状态
    $('.x-show').click(function () {
        if ($(this).attr('status') == 'true') {
            $(this).html('&#xe625;');
            $(this).attr('status', 'false');
            cateId = $(this).parents('tr').attr('cate-id');
            $("tbody tr[fid=" + cateId + "]").show();
        } else {

            $(this).html('&#xe623;');
            $(this).attr('status', 'true');
            cateId = $(this).parents('tr').attr('cate-id');
            cateIds = [];
            getCateId(cateId);

            for (var i in cateIds) {
                $("tbody tr[cate-id=" + cateIds[i] + "]").hide().find('.x-show').html('&#xe623;').attr('status', 'true');
            }
        }
    })


    /** 公共菜单树单个展开与合并 */
    $('.show_menu').click(function () {
        let state = $(this).attr('data-state');
        let id = $(this).attr('data-id');
        if (state === 'hide') {
            $(".pid_" + id).css('display', '');
            $(this).attr('data-state', 'show');
            $(this).html('&#xe625;');
        } else {
            $(".pp" + id).css('display', 'none').find('.show_menu').attr('data-state', 'hide').html('&#xe623;');
            $(this).attr('data-state', 'hide');
            $(this).html('&#xe623;');
        }
    });
});

function tableRender(id, cols, url, totalRow) {
    //执行渲染
    table.render({
        elem: id
        , cols: [cols]
        , page: true
        , url: url
        , id: 'form_table'
        , totalRow: totalRow
        , cellMinWidth: 80
        , limit: 20
        , limits: [20, 40, 60, 80, 100]
        , size: 'sm'
        , even: true
        , done: function (res, curr, count) {
            if (res.census) {
                var html = '';
                for (var i = 0; i < res.census.length; i++) {
                    html += '<div>' + res.census[i].title + '：' + res.census[i].value + '</div>';
                }
                $(".statistics_list").html(html);
            }
        }
    });
}

function layerLoad() {
    layer.msg('<div><i class="layui-icon layui-icon-loading-1 layui-anim layui-anim-rotate layui-anim-loop"></i> 加载中....', {
        shade: 0.8,
        time: 99999
    });
}


/** 菜单树全局展开与折叠 */
function openAllCate(that) {
    var text = $('.show_text').text();
    if (text == '展开') {
        $(".showAll").show();
        $('.show_text').text('折叠');
        $('.x-show').attr('status', 'false').html('&#xe625;');
    } else {
        $(".showAll").hide();
        $('.show_text').text('展开');
        $('.x-show').attr('status', 'true').html('&#xe623;');

    }

}

/** 公共获取表格内选中的数据 */
function getTable() {
    return table.checkStatus('form_table');
}


/** 公共弹出层 */
function zhiju_show(title, url, w, h, full = 0) {
    if (title == null || title == '') title = false;
    if (url == null || url == '') url = "404.html";
    if (w == null || w == '' || $(window).width() < w) w = ($(window).width() * 0.9);
    if (h == null || h == '' || $(window).height() < h) h = ($(window).height() - 50);
    if (full == '1') {
        let index = layer.open({
            type: 2,
            area: [w + 'px', h + 'px'],
            fix: false, //不固定
            maxmin: true,
            shadeClose: true,
            shade: 0.4,
            anim: 2,
            title: title,
            content: url,

        });
        layer.full(index);
    } else {
        layer.open({
            type: 2,
            area: [w + 'px', h + 'px'],
            fix: false, //不固定
            maxmin: true,
            shadeClose: true,
            shade: 0.4,
            anim: 2,
            title: title,
            content: url
        });
    }
}

/** 公共删除 */
function destroys(obj, url, id, key, val) {
    layer.confirm('确认要删除吗？', function (index) {
        layer.load(2);
        $.post(url, {id: id, key: key, val: val}, function (data) {
            layer.closeAll();
            if (data.code == 1) {
                $(obj).parents("tr").remove();
                notify.success(data.msg);
            } else {
                notify.error(data.msg);
            }
        });
    });
}

$(".search_open").click(function () {
    var text = $(this).text();
    if (text == '展开') {
        $(".hidden").removeClass('layui-hide');
        $(this).text('收起').addClass('search_close').removeClass('search_open');
    } else {
        $(".hidden").addClass('layui-hide');
        $(this).text('展开').addClass('search_open').removeClass('search_close');
    }
});